//
//  Rating.swift
//  classWork4_5repeat
//
//  Created by Qingke on 16/4/7.
//  Copyright © 2016年 Qingke. All rights reserved.
//

import UIKit

class Rating: UIView {
    //MARK :属性
    private var buttonHeight :CGFloat = 44
    private var buttonWidth : CGFloat = 44
    private var space : CGFloat = 5
    private var starNumber : Int = 5
    
    //这里使用编辑器能有效监控数字更改， 保证后面的直接赋值的使用
    var rating: Int = 0 {
        didSet{
            print("oldValue=\(oldValue),newValue =\(rating)")
            if oldValue != rating {
                up()
            }
        }
    }
    
    var buttons = [UIButton]()
    
    let emptyStar = UIImage(named: "emptyStar")
    let filledStar = UIImage (named: "filledStar")
    
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        
        for i in 0..<starNumber{
            let button = UIButton()
            button.backgroundColor = UIColor.redColor()
            button.tag = i + 1
            button.setImage(emptyStar, forState: .Normal)
            button.setImage(filledStar, forState: .Selected)
            button.setImage(filledStar, forState: [.Selected ,.Highlighted])
            button.addTarget(self, action: "ratingControlTapped:", forControlEvents: UIControlEvents.TouchDown)
            //这里的冒号有讲究,冒号的作用表示有一个参数，由于swift语法中，头参数的外部名可以省略，所以就直接： 省略了当前button 对象
            //如果是多个参数就用 "ratingControlTapped: second:"
            buttons.append(button)
            button.adjustsImageWhenHighlighted = false
            addSubview(button)
        }
    }
    
    override func layoutSubviews() {
        var buttonX: CGFloat = 0
        let buttonY: CGFloat = 0
        for button in buttons {
            button.frame = CGRect(x: buttonX, y: buttonY, width: buttonWidth, height: buttonHeight)
            buttonX += (buttonWidth + space)
        }
    }
    
    func ratingControlTapped (button:UIButton) {
        
        rating = button.tag
        print("点了评分按钮\(rating)分")
        
    }
    
    func up() {
        for button in buttons{
            if button.tag <= rating{
                button.selected = true
            } else {
                button.selected = false //所有的UI 都有Tag 属性
            }
        }
    }
//如果没有重新设置view的边框大小，就会导致viewcontroller 不能正常加载。如没有相对印的功能
    override func intrinsicContentSize() -> CGSize {
        return CGSize(width: (buttonWidth+space) * CGFloat(starNumber), height: buttonHeight)
    }


    
    
}
